//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Resource Application Block
//===============================================================================

using System;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation;
using EntLibContrib.Resource.Instrumentation;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif

namespace EntLibContrib.Resource.Instrumentation.Tests
{
	[TestClass]
	public class ResourceEventLogFixture
	{
		private const string instanceName = "test";
		private const string exceptionMessage = "exception message";
		private const string errorMessage = "error message";
		private const string key = "key";

		private NoPrefixNameFormatter formatter;

		[TestInitialize]
		public void SetUp ()
		{
			formatter = new NoPrefixNameFormatter();
		}

		[TestMethod]
		public void ResourceFailureWithInstrumentationDisabledDoesNotWriteToEventLog ()
		{
			ResourceInstrumentationListener listener = new ResourceInstrumentationListener(instanceName, false, false, false, formatter);
			Exception exception = new Exception(exceptionMessage);

			ResourceFailureEventArgs args = new ResourceFailureEventArgs(errorMessage, exception);

			using ( EventLog eventLog = GetEventLog() )
			{
				int eventCount = eventLog.Entries.Count;

				listener.ResourceFailed(null, args);

				Assert.AreEqual(eventCount, eventLog.Entries.Count);
			}
		}

		[TestMethod]
		public void ResourceFailureWithInstrumentationEnabledDoesWriteToEventLog ()
		{
			ResourceInstrumentationListener listener = new ResourceInstrumentationListener(instanceName, false, true, false, formatter);
			Exception exception = new Exception(exceptionMessage);

			ResourceFailureEventArgs args = new ResourceFailureEventArgs(errorMessage, exception);

			using ( EventLog eventLog = GetEventLog() )
			{
				int eventCount = eventLog.Entries.Count;

				listener.ResourceFailed(null, args);

				Assert.AreEqual(eventCount + 1, eventLog.Entries.Count);
				Assert.IsTrue(eventLog.Entries[eventCount].Message.IndexOf(exceptionMessage) > -1);
			}
		}

		private static EventLog GetEventLog ()
		{
			return new EventLog("Application", ".", ResourceInstrumentationListener.EventLogSourceName);
		}
	}
}